package com.sky.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.InputStream;

@Data
@AllArgsConstructor
@Slf4j
public class ViduUtil {

    private String token;

    private static final String SUBMIT_URL = "https://api.vidu.cn/ent/v2/img2video";
    private static final String QUERY_URL_TEMPLATE = "https://api.vidu.cn/ent/v2/tasks/%s/creations";

    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    /**
     * 提交任务，返回 task_id
     */
    public String submitTask(String model, String imageUrl, String prompt, int duration) {
        try {
            HttpPost httpPost = new HttpPost(SUBMIT_URL);
            httpPost.setHeader("Authorization", "Token " + token);
            httpPost.setHeader("Content-Type", "application/json");

            JSONObject json = new JSONObject();
            json.put("model", model);
            json.put("images", new String[]{imageUrl});
            json.put("prompt", prompt);
            json.put("duration", duration);
            json.put("seed", 0);
            json.put("resolution", "1080p");
            json.put("movement_amplitude", "auto");

            httpPost.setEntity(new StringEntity(json.toJSONString(), "UTF-8"));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String res = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("提交任务返回: {}", res);

                JSONObject resJson = JSONObject.parseObject(res);
                return resJson.getString("task_id");
            }
        } catch (Exception e) {
            log.error("提交任务失败", e);
        }

        return null;
    }

    /**
     * 查询任务，返回视频URL（1小时有效）
     */
    public String queryResult(String taskId) {
        String url = String.format(QUERY_URL_TEMPLATE, taskId);
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", "Token " + token);
            httpGet.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                String res = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("查询任务返回: {}", res);

                JSONObject resJson = JSONObject.parseObject(res);
                String state = resJson.getString("state");
                if (!"success".equals(state)) {
                    log.info("当前状态: {}", state);
                    return null;
                }

                JSONArray creations = resJson.getJSONArray("creations");
                if (creations != null && !creations.isEmpty()) {
                    return creations.getJSONObject(0).getString("url");
                }
            }
        } catch (Exception e) {
            log.error("查询任务失败", e);
        }

        return null;
    }

    /**
     * 下载视频文件到本地
     */
    public boolean downloadFile(String fileUrl, String savePath) {
        try {
            HttpGet httpGet = new HttpGet(fileUrl);

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                log.error("下载失败: 无内容");
                return false;
            }

            try (InputStream is = entity.getContent();
                 FileOutputStream fos = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[4096];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
                log.info("下载成功，保存为：{}", savePath);
                return true;
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
        return false;
    }
}
